import * as types from '../types';
import axios from 'axios';
import { findIndex } from 'lodash';

export default {
  state: {
    data: []
  },
  getters: {
    apps: state => {
      let rsp = {};
      for (let i = 0; i != state.data.length; ++i) {
        rsp[state.data[i].appid] = state.data[i];
      }
      return rsp;
    }
  },
  mutations: {
    [types.SET_APPS]: (state, payload) => {
      state.data = [];
      for (let i = 0; i != payload.length; ++i) {
        state.data.push(payload[i]);
      }
    },
    [types.RESET_APPS]: (state) => {
      state.data = [];
    },
    [types.ADD_APP]: (state, payload) => {
      state.data.push(payload);
    },
    [types.REMOVE_APP]: (state, appid) => {
      let idx = findIndex(state.data, item => item.appid === appid);
      if (idx === -1) {
        console.error('cannot found appid??' + appid);
        return;
      }
      state.data.splice(idx, 1);
    }
  },
  actions: {
    load_apps: ({ commit }) => {
      axios.get("/apps/").then(response => {
        commit(types.SET_APPS, response.data);
      }).catch(err => {
        console.log('error occurd');
        console.error(err);
      });
    },
    add_app: ({ commit }, payload) => {
      return new Promise((resolve, reject) => {
        axios.post("/apps/", payload).then(response => {
          commit(types.ADD_APP, response.data);
          resolve(response);
        }).catch(err => {
          console.log('add app, server failed.');
          console.log(err);
          reject(err);
        });
      });
    },
    remove_app: ({ commit }, appid) => {
      axios.delete("/apps/" + appid + "/").then(response => {
        commit(types.REMOVE_APP, appid);
      }).catch(err => {
        console.log('remove app failed');
        console.error(err);
      });
    },
  }
}